//
//  StockAnalysisViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/7/15.
//  Copyright (c) 2015年 RuiBen. All rights reserved.
//

#import "ScanHomeViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@interface ScanHomeViewController ()
{
   // NSMutableArray *scanStockResultArray;
    
    
//    NSMutableArray *itemCodeArray;
//    NSMutableArray *itemNameArray;
//    NSMutableArray *itemWhereArray;
//    NSMutableArray *itemPriceArray;
//    NSMutableArray *itemUrlArray;
//    NSMutableArray *itemWeightArray;
//    
//    NSMutableArray *itemSeriesNameArray;
//    NSMutableArray *itemTypeNameArray;
//    NSMutableArray *itemInDateArray;
//    NSMutableArray *notExistArray;
    
    NSMutableArray *stockItemCodeArray;
    NSMutableArray *stockItemNameArray;
    NSMutableArray *stockItemWhereArray;
    NSMutableArray *stockItemPriceArray;
    NSMutableArray *stockItemUrlArray;
    NSMutableArray *stockItemWeightArray;
   
    NSMutableArray *stockNotExistArray;
}
@property (nonatomic,retain) AVAudioPlayer *myBackMusic;
@end

@implementation ScanHomeViewController
@synthesize myBackMusic;
-(void)viewWillAppear:(BOOL)animated
{
   
   // NSLog(@"rrrreeeeee");
    if ([Global getLoginToken].length>0) {
  //  scanTypeStr=@"";
        
   [Global setScanID:1];
       // [Global setHomeCustomID:10];
    [_scanMemberBtn setImage:[UIImage imageNamed:@"saohuiyuan_normal.png"] forState:UIControlStateNormal];
    [_scanStockBtn setImage:[UIImage imageNamed:@"saokucun_normal.png"] forState:UIControlStateNormal];
    [_scanShopBtn setImage:[UIImage imageNamed:@"saogouwu_normal.png"] forState:UIControlStateNormal];

   // _scanCountLabel.text=@"0";
    _searchTextField.text=@"";
    
    isDown=NO;
    if (_captureSession!=nil) {
    [_captureSession stopRunning];
    [_videoPreviewLayer removeFromSuperlayer];
    _captureSession = nil;
        }
    if (_timer==nil) {
            
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
       
        [self startRead];
    }

    [self initScanResult];

    _scanStockCountBtn.layer.borderColor=[[UIColor colorWithRed:70.0f/255.0f green:70.0f/255.0f blue:70.0f/255.0f alpha:1.0f] CGColor];
    _scanStockCountBtn.layer.borderWidth= 1.0f;
    _scanStockCountBtn.layer.cornerRadius=45;
    [_scanStockCountBtn addTarget:self action:@selector(scanStockCountBtnClick) forControlEvents:UIControlEventTouchUpInside];
        num=0;
        
    for (UIView *v in _viewContainer.subviews) {
            if (v.tag>999) {
                [v removeFromSuperview];
            }
            
        }
        _scanStockCountBtn.hidden=YES;
        
       // scanTypeStr=@"SCANSHOP";
        if ([_scanTypeStr isEqualToString:@"SCANSHOP"]) {
        
        _scanStockCountBtn.hidden=YES;
  
        [_scanStockBtn setImage:[UIImage imageNamed:@"saokucun_normal.png"] forState:UIControlStateNormal];
        [_scanShopBtn setImage:[UIImage imageNamed:@"saogouwu_hight.png"] forState:UIControlStateNormal];
        }
        else
        {
            _scanStockCountBtn.hidden=NO;
            [_scanStockBtn setImage:[UIImage imageNamed:@"saokucun_hight.png"] forState:UIControlStateNormal];
            [_scanShopBtn setImage:[UIImage imageNamed:@"saogouwu_normal.png"] forState:UIControlStateNormal];
        }
        
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"mp3"];       //创建音乐文件路径
        NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
        
        AVAudioPlayer *thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
        //
        self.myBackMusic = thePlayer;    //赋值给自己定义的类变量
        
      
        musicURL =nil;
        thePlayer=nil;;
        [myBackMusic prepareToPlay];
        [myBackMusic setVolume:1];   //设置音量大小
        myBackMusic.numberOfLoops = 1;//设置音乐播放次数  -1为一直循环
        

        [_viewContainer bringSubviewToFront:_bgImageView
         ];

    [_viewContainer bringSubviewToFront:_searchViewContainer];
    [_viewContainer bringSubviewToFront:_lightImageView];
    [_viewContainer bringSubviewToFront:_scanMemberBtn];
    [_viewContainer bringSubviewToFront:_scanShopBtn];
    [_viewContainer bringSubviewToFront:_scanStockBtn];
    [_viewContainer bringSubviewToFront:_scanStockCountBtn];
    [_viewContainer bringSubviewToFront:_lineLabel
         ];
        
    }
}
-(void)initScanResult
{
     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
     if ([userDefaults objectForKey:@"SCANSTOCKITEMCODE"]) {
         stockItemCodeArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMCODE"]];
         stockItemNameArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMNAME"]];
         stockItemWhereArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMWHERE"]];
         stockItemPriceArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMPRICE"]];
         stockItemUrlArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMURL"]];
         stockItemWeightArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMWEIGHT"]];
        
         stockNotExistArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:@"SCANSTOCKITEMNOTEXIST"]];

     }
     else{
         stockItemCodeArray=[NSMutableArray array];
         stockItemNameArray=[NSMutableArray array ];
         stockItemWhereArray=[NSMutableArray array ];
         stockItemPriceArray=[NSMutableArray array ];
         stockItemUrlArray=[NSMutableArray array ];
         stockItemWeightArray=[NSMutableArray array ];
         
         stockNotExistArray=[NSMutableArray array];

     }
     _scanCountLabel.text=[NSString stringWithFormat:@"%ld",(unsigned long)stockItemCodeArray.count];
}
-(IBAction)scanMemberBtnClick:(id)sender
{
    _scanTypeStr=@"SCANMEMBER";
    _scanStockCountBtn.hidden=YES;
    [_scanMemberBtn setImage:[UIImage imageNamed:@"saohuiyuan_hight.png"] forState:UIControlStateNormal];
    [_scanStockBtn setImage:[UIImage imageNamed:@"saokucun_normal.png"] forState:UIControlStateNormal];
    [_scanShopBtn setImage:[UIImage imageNamed:@"saogouwu_normal.png"] forState:UIControlStateNormal];
     //[self startRead];
}
-(IBAction)scanShopBtnClick:(id)sender
{
    _scanTypeStr=@"SCANSHOP";
     _scanStockCountBtn.hidden=YES;
    [_scanMemberBtn setImage:[UIImage imageNamed:@"saohuiyuan_normal.png"] forState:UIControlStateNormal];
    [_scanStockBtn setImage:[UIImage imageNamed:@"saokucun_normal.png"] forState:UIControlStateNormal];
    [_scanShopBtn setImage:[UIImage imageNamed:@"saogouwu_hight.png"] forState:UIControlStateNormal];
    // [self startRead];

}
-(IBAction)scanStockBtnClick:(id)sender
{
    _scanCountLabel.text=[NSString stringWithFormat:@"%ld",(unsigned long)stockItemCodeArray.count];

     _scanTypeStr=@"SCANSTOCK";
     _scanStockCountBtn.hidden=NO;
    [_scanMemberBtn setImage:[UIImage imageNamed:@"saohuiyuan_normal.png"] forState:UIControlStateNormal];
    [_scanStockBtn setImage:[UIImage imageNamed:@"saokucun_hight.png"] forState:UIControlStateNormal];
    [_scanShopBtn setImage:[UIImage imageNamed:@"saogouwu_normal.png"] forState:UIControlStateNormal];
// [self startRead];
}
-(void)scanCancelBtnClick
{
    if ([self.delegate respondsToSelector:@selector(scanHomeCancelClick)]) {
        
        [self.delegate scanHomeCancelClick];
    }
    
}
-(void)lineAnimation
{
    if (isDown==NO) {
        num++;
        
        _lineLabel.frame=CGRectMake(_lineLabel.frame.origin.x, 170+2*num,_lineLabel.frame.size.width, _lineLabel.frame.size.height);
        if (2*num==330) {
            isDown=YES;
            
        }
    }
    else
    {
        num--;
        _lineLabel.frame=CGRectMake(_lineLabel.frame.origin.x, 170+2*num,_lineLabel.frame.size.width, _lineLabel.frame.size.height);
        
        if (num==0) {
            isDown=NO;
        }
    }
}
-(BOOL)startRead
{
    NSError *error;
    
    AVCaptureDevice *captureDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        // NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
  // if (_captureSession==nil) {
        
    
    _captureSession = [[AVCaptureSession alloc] init];
    if ([_captureSession canAddInput:input]) {
        [_captureSession addInput:input];
    }
    
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    captureMetadataOutput.rectOfInterest=self.view.frame;
    if ([_captureSession canAddOutput:captureMetadataOutput]) {
        [_captureSession addOutput:captureMetadataOutput];
    }
    
    
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    captureMetadataOutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code];
   
    
    [captureMetadataOutput setRectOfInterest:CGRectMake(0.25, 0.25, 0.85, 0.35)];
   // }
//    if(_videoPreviewLayer==nil)
//    {
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
      [_videoPreviewLayer setFrame:_viewContainer.layer.bounds];
   
    [_videoPreviewLayer setBackgroundColor:(__bridge CGColorRef)[Global parseColor:WESTORE_TRANSCLUCENT]];
    
      [_viewContainer.layer addSublayer:_videoPreviewLayer];
   // }
    [self changePreviewOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
    [_captureSession startRunning];
    return YES;
}
-(void)stopReading{
    
    [_captureSession stopRunning];
    _captureSession = nil;
    
    [_videoPreviewLayer removeFromSuperlayer];
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
      //  NSLog(@"stringValue====%@",stringValue);
        // if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]&&[metadataObject.stringValue hasPrefix:@"S"]) {
        
        // AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code
        
        // if ([[metadataObject type] isEqualToString:AVMetadataObjectTypeQRCode]||[[metadataObject type] isEqualToString:AVMetadataObjectTypeEAN13Code]||[[metadataObject type] isEqualToString:AVMetadataObjectTypeCode128Code]) {
        if ([_scanTypeStr isEqualToString:@"SCANMEMBER"]) {
            [self performSelectorOnMainThread:@selector(loadMemberVC) withObject:nil waitUntilDone:NO];
           [self stopReading];
            [_timer invalidate];
            _timer=nil;
            
            
        }

        if ([_scanTypeStr isEqualToString:@"SCANSHOP"]) {
        [self performSelectorOnMainThread:@selector(loadShopVC) withObject:nil waitUntilDone:NO];
            [self stopReading];
            [_timer invalidate];
            _timer=nil;

            
        }
        if ([_scanTypeStr isEqualToString:@"SCANSTOCK"]) {
            [self performSelectorOnMainThread:@selector(loadStockVC) withObject:nil waitUntilDone:NO];

        }
    }
    
//    [_captureSession stopRunning];
//    //[_videoPreviewLayer removeFromSuperlayer];
//    _captureSession = nil;
//    [timer invalidate];
//    timer=nil;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
   // [_searchTextField resignFirstResponder];
    if (textField==_searchTextField) {
        stringValue=textField.text;
        if ([_scanTypeStr isEqualToString:@"SCANMEMBER"]) {
           // [self performSelectorOnMainThread:@selector(loadMemberVC) withObject:nil waitUntilDone:NO];
            [self loadMemberVC];
            
        }
        
        if ([_scanTypeStr isEqualToString:@"SCANSHOP"]) {
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            [self loadShopVC];
            
            
        }
        if ([_scanTypeStr isEqualToString:@"SCANSTOCK"]) {
           // [self performSelectorOnMainThread:@selector(loadStockVC) withObject:nil waitUntilDone:NO];
             [self loadStockVC];
            
        }

    }
     _searchTextField.text=@"";
    return YES;
    
}

-(void)loadMemberVC
{
    if ([self.delegate respondsToSelector:@selector(scanHomeMemberResult:)]) {
        
        [self.delegate scanHomeMemberResult:stringValue];
    }

   
}
-(void)loadShopVC
{
    [self.myBackMusic play];
    //    [Global setScanResultStr:stringValue];
    if ([self.delegate respondsToSelector:@selector(scanHomeShopResult:)]) {
        
        [self.delegate scanHomeShopResult:stringValue];
    }
     //[_captureSession startRunning];
    
}
-(void)loadStockVC
{
    // NSLog(@"notExistArray===%@",notExistArray);
     if (![stockItemCodeArray containsObject:stringValue]&&![stockNotExistArray containsObject:stringValue]) {
        
    [self requestItemDetail:stringValue];
       
    }
}
-(void)requestItemDetail:(NSString *)codeStr
{
    if ([Global getLoginToken].length>0) {
        //[Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        [params setObject:codeStr forKey:@"ItemCode"];
        [HttpRequest requestData:@"Product/ItemDetail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
           // NSLog(@"tttttttttt====%@",severDataDict.dataDict);
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    
                    [self setScanStockStringValue:stringValue urlStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"ImageUrl"] typeStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"ItypeName"] seriesStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"SeriesName"] dateStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"InDate"] weightStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"Gram"] priceStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"Price"] whereStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"WhsName"] itemNameStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"ItemName"] codeStr:[[severDataDict.dataDict objectForKey:@"DataItem"] objectForKey:@"ItemCode"]];
                    
                }
                else
                {
                    [stockNotExistArray addObject:codeStr];
                   // [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    
//                    if (timer!=nil) {
//                        [timer invalidate];
//                        timer=nil;
//                    }
//                    UIViewController *controller=[[GlobalViewController alloc]init];
//                    [self.navigationController pushViewController:controller animated:YES];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                          [self stopReading];
                        if (_timer!=nil) {
                            [_timer invalidate];
                            _timer=nil;
                        }
                      [Global loginViewController:self noteStr:requestResultStr];
                      //  [Global loginViewController:self];
                    }

                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }
}
-(void)setScanStockStringValue:(NSString *)str urlStr:(NSString *)urlStr typeStr:(NSString *)typeStr seriesStr:(NSString *)seriesStr dateStr:(NSString *)dateStr
                     weightStr:(NSString *)weightStr priceStr:(NSString *)priceStr whereStr:(NSString *)whereStr itemNameStr:(NSString *)itemNameStr codeStr:(NSString *)codeStr
{
    if (![stockItemCodeArray containsObject:str]&&![stockItemCodeArray containsObject:codeStr]) {
        //[_stockResultArray addObject:str];
        [self.myBackMusic play];
        [stockItemUrlArray insertObject:urlStr atIndex:0];
        [stockItemWeightArray insertObject:weightStr atIndex:0];
        [stockItemPriceArray insertObject:priceStr atIndex:0];
        [stockItemWhereArray insertObject:whereStr atIndex:0];
        [stockItemNameArray insertObject:itemNameStr atIndex:0];
        [stockItemCodeArray insertObject:codeStr atIndex:0];
        //NSLog(@"itemCodeArray111===%@",itemCodeArray);

     _scanCountLabel.text=[NSString stringWithFormat:@"%ld",(unsigned long)stockItemCodeArray.count];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:stockItemCodeArray forKey:@"SCANSTOCKITEMCODE"];
        [userDefaults setObject:stockItemNameArray forKey:@"SCANSTOCKITEMNAME"];
        [userDefaults setObject:stockItemWhereArray forKey:@"SCANSTOCKITEMWHERE"];
        [userDefaults setObject:stockItemPriceArray forKey:@"SCANSTOCKITEMPRICE"];
        [userDefaults setObject:stockItemUrlArray forKey:@"SCANSTOCKITEMURL"];
        [userDefaults setObject:stockItemWeightArray forKey:@"SCANSTOCKITEMWEIGHT"];
        [userDefaults setObject:stockNotExistArray forKey:@"SCANSTOCKITEMNOTEXIST"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
-(void)scanStockCountBtnClick
{
    [_captureSession stopRunning];
    [_videoPreviewLayer removeFromSuperlayer];
    _captureSession = nil;
    [_timer invalidate];
    _timer=nil;
    
    if ([self.delegate respondsToSelector:@selector(scanHomeStockResult)]) {
        
        [self.delegate scanHomeStockResult];
    }

}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self changePreviewOrientation:(UIInterfaceOrientation)toInterfaceOrientation];
}
- (void)changePreviewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   // [CATransaction begin];
    [CATransaction begin];
    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        //  g_orientation = UIImageOrientationUp;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
        
    }else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        //  g_orientation = UIImageOrientationDown;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
        
    }else if (interfaceOrientation == UIDeviceOrientationPortrait){
        //  g_orientation = UIImageOrientationRight;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        
    }else if (interfaceOrientation == UIDeviceOrientationPortraitUpsideDown){
        //  g_orientation = UIImageOrientationLeft;
        _videoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
    }
    [CATransaction commit];
    
// [CATransaction commit];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
